package http;

import com.alibaba.fastjson.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:Eric
 * @date:2021/7/5 客户端
 * 初始化线程
 * 初始化channel
 * 绑定channle
 */
public class HttpClient {


    /**
     * 连接服务器
     *
     * @param host
     * @param port
     * @throws Exception
     */
    public void connect(String host, int port, String path, Map<String, String> contentMap) throws Exception {

        //初始化线程
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //请求编码
                                    .addLast(new HttpRequestEncoder())
                                    //响应解码
                                    .addLast(new HttpResponseDecoder())
                                    //自定义处理器
                                    .addLast(new HttpClientHandler());
                        }
                    });
            ChannelFuture connect = bootstrap.connect(host, port);
            URI uri = new URI("http://" + host + ":" + port + "/" + path);
            String content = JSON.toJSONString(contentMap);
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    String.valueOf(uri),
                    Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));
            request.headers()
                    .set(HttpHeaderNames.HOST, host)
                    .set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON)
                    .set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes())
                    .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            connect.channel().writeAndFlush(request);
            connect.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();

        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> contentMap = new HashMap<>(8);
        contentMap.put("aaa", "111");
        contentMap.put("bbb", "222");
        new HttpClient().connect("127.0.0.1", 8088, "abc", contentMap);
    }
}
